package com.cloudcc.mobile.view.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cloudcc.cloudframe.bus.DynamicEventList.SendDynamicEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.AppManager;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.ImageGridAdapter;
import com.cloudcc.mobile.adapter.ImageGridAdapter.OnAddImageListener;
import com.cloudcc.mobile.adapter.ImageGridAdapter.OnShowImageListener;
import com.cloudcc.mobile.adapter.ImageGridAdapter.OndeleteListener;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.EventTaskEntity;
import com.cloudcc.mobile.entity.map.MapLocation;
import com.cloudcc.mobile.event.EventTaskEventList.SendEventEvent;
import com.cloudcc.mobile.event.refresh.RefreshDynamicListEvent;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.network.QianDaoNewWork;
import com.cloudcc.mobile.presenter.EventOrTaskPresenter;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.customer.CustomerActivity;
import com.cloudcc.mobile.weight.GridViewForListView;

/**
 * 签到编辑类
 * 
 * @author Administrator
 * 
 */
public class EditorActivity extends BaseActivity implements IEventLife {

	@Bind(R.id.neirong)
	EditText etContent;

	@Bind(R.id.fromname)
	TextView fromname;
	@Bind(R.id.lefttext)
	TextView tvAddress;// 位置
	@Bind(R.id.righttxt)
	TextView tvSubject;// 主题

	@Bind(R.id.addimage)
	ImageView addimage;
	@Bind(R.id.takephoto)
	ImageView takephoto;

	@Bind(R.id.leftr)
	RelativeLayout left;
	@Bind(R.id.rightr)
	RelativeLayout right;

	@Bind(R.id.add_pic_grid)
	GridViewForListView addpic;

	public MapLocation currentLoc = new MapLocation();// 位置

	private List<AddImageInfo> mAddImageArray = new ArrayList<AddImageInfo>();//将要上传的图片的结合
	private ImageGridAdapter imageGridAdapter;
	private int TO_PIC_IMAGE = 1;
	private int TO_PHOTO_IMAGE = 2;
	private String imagename;
	private String eventContent;// 签到内容
	private String qidaoName;
	private String eventWhoId;// 潜在客户用的who 潜在客户对象
	private String eventSubject;// 主题 类型
	private String from;
	private String key;
	private String reuevantType = "";
	boolean hasAddress = true;

	EventOrTaskPresenter mPresenter = new EventOrTaskPresenter();

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		register();
		setupView();
		fillData();
	}

	@OnClick(R.id.takephoto)
	public void onClickTakePhoto() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			File dir = new File(Environment.getExternalStorageDirectory() + "/"
					+ "CloudCC/photo/");
			if (!dir.exists())
				dir.mkdirs();
			imagename = Tools.getTimeName(System.currentTimeMillis());
			Intent intent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			File f = new File(dir, imagename);// localTempImgDir和localTempImageFileName是自己定义的名字
			Uri u = Uri.fromFile(f);
			intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
			startActivityForResult(intent, TO_PHOTO_IMAGE);

		} else {
			Tools.showInfo(EditorActivity.this, "请插入SD卡");
		}

	}

	@OnClick(R.id.addimage)
	public void onClickChoicePhoto() {
		Intent intent = new Intent(mContext, SelectPhotoActivity.class);
		startActivityForResult(intent, TO_PIC_IMAGE);

	}

	@OnClick(R.id.quxiao)
	public void onClickBack() {
		finish();
	}

	@OnClick(R.id.leftr)
	public void onClickAddress() {
		tvAddress.setText(hasAddress ? currentLoc.getAddress() : "插入位置");
		hasAddress = !hasAddress;
	}

	@OnClick(R.id.sendd)
	public void onClickSend() {
		showWainting("正在签到,请稍等...");
		AppContext.isSelectedNum = 0;
		eventContent = StringUtils.isBlank(etContent.getText().toString()) ? etContent
				.getHint().toString() : etContent.getText().toString();

		EventTaskEntity event = new EventTaskEntity();
		// 所有人
		event.setBelongtoid(UserManager.getManager().getUser().userId);
		event.setBelongtoidccname(UserManager.getManager().getUser().userName);
		event.setOwnerid(UserManager.getManager().getUser().userId);

		// 设置task 还是event
		if (TextUtils.equals(key, String.valueOf(2))) {// 2代表task
			event.setIstask(String.valueOf(1));
			event.setExpiredate(Tools.getYMDTime(System.currentTimeMillis()));
		} else {
			event.setIstask(String.valueOf(0));
			String begintime = Tools
					.getTime(System.currentTimeMillis() - 600000);
			String endtime = Tools.getTime(System.currentTimeMillis() - 500000);
			event.setBegintime(begintime);
			event.setEndtime(endtime);
		}
		//区分 联系人 潜在客户 跟 客户 的不同字段赋值
		if (StringUtils.isNotBlank(eventWhoId)) {
			String eventSubTypeId = StringUtils.substring(eventWhoId, 0, 3);
			if (TextUtils.equals(eventSubTypeId, "003")
					|| TextUtils.equals(eventSubTypeId, "004")) {// 联系人 潜在客户
				event.setWhoid(eventWhoId);
				event.setWhoobj(eventSubTypeId);
			} else {// 客户
				event.setRelateid(eventWhoId);
				event.setRelateobj(eventSubTypeId);
			}
		}
		//备注
		event.setRemark(eventContent);
		event.setSubject(qidaoName);
		event.setIsemailnotification(String.valueOf(true));
		event.setIsremider(String.valueOf(true));
		event.setType(eventSubject);
		event.setName(eventSubject);
		event.setIscompleted(String.valueOf(1));
		event.setStatus("已结束");
		if(hasAddress&&null!=currentLoc){
			event.setPosition(currentLoc.getAddress());
		}
		mPresenter.sendEventAndInsertTimeLine(event, currentLoc, mAddImageArray);

	}

	private void onHasSend() {
		if (key.equals("2") || key.equals("1")) {
			finish();
		} else {
			finish();
			AppManager.getInstance().finishActivity(CustomerActivity.class);
			AppManager.getInstance().finishActivity(MapsActivity.class);
		}
	}

	// 获取控件
	public void setupView() {
		tvAddress.setText("正在定位");
		qidaoName = getIntent().getStringExtra("CustomerActivity");
		eventWhoId = getIntent().getStringExtra("urlId");
		reuevantType = getIntent().getStringExtra("reuevantType");
		from = getIntent().getStringExtra("from");
		key = getIntent().getStringExtra("key");
		eventSubject = getIntent().getStringExtra("name");
		currentLoc = (MapLocation) getIntent().getSerializableExtra(
				"MapsActivity");
		if (currentLoc == null) {// 没有传递过位置来 重新定位
			LocationManager.getInstance().registerListener(mListener);
			LocationManager.getInstance().requestLocal();
		}
	}

	// 初始化数据
	private void fillData() {
		imageGridAdapter = new ImageGridAdapter(this, mAddImageArray);
		addpic.setAdapter(imageGridAdapter);
		setAdapterListener();
		if (currentLoc != null) {
			if (currentLoc.getAddress().length() > 14) {
				tvAddress.setText(currentLoc.getAddress().substring(0, 13)
						+ "...");
			} else {
				tvAddress.setText(currentLoc.getAddress());
			}
		}
		if (from.equals("map")) {
			tvSubject.setText(eventSubject);
			eventSubject = "签到拜访";
			fromname.setText("活动:" + reuevantType);
			etContent.setHint("活动:" + reuevantType);
		} else {
			// from=web
			fromname.setText("活动:" + reuevantType);
			etContent.setHint("活动:" + reuevantType);
			if (AppContext.relevantName != null) {
				tvSubject.setText(AppContext.relevantName);
			}
		}
	}

	// GridView监听
	private void setAdapterListener() {
		addpic.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				imageGridAdapter.setDeleteModel(false);
				return true;
			}
		});
		imageGridAdapter.setOnAddImageListener(new OnAddImageListener() {
			@Override
			public void add() {
				AppContext.isSelectedNum = mAddImageArray.size();
				Intent intent = new Intent(mContext, SelectPhotoActivity.class);
				startActivityForResult(intent, TO_PIC_IMAGE);
			}
		});
		imageGridAdapter.setOndeleteListener(new OndeleteListener() {
			@Override
			public void delete(int posion) {
				mAddImageArray.remove(posion);
				if (mAddImageArray.size() == 0) {
					imageGridAdapter.setDeleteModel(false);
				} else {
					imageGridAdapter.notifyDataSetChanged();
				}

			}
		});
		imageGridAdapter.setOnShowImageListener(new OnShowImageListener() {
			@Override
			public void show(int posion) {
				File file = new File(mAddImageArray.get(posion).getImagePath());
				Intent it = new Intent(Intent.ACTION_VIEW);
				Uri mUri = Uri.parse("file://" + file.getPath());
				it.setDataAndType(mUri, "image/*");
				startActivity(it);
			}
		});

	}
	
	

	/**
	 * 发送成功
	 * 
	 * @param event
	 */
	public void onEventMainThread(SendEventEvent event) {
		dismissWainting();
		if (event.isOk()) {
			showToast("签到成功!");
			RefreshDynamicListEvent refreshDynamicListEvent = new RefreshDynamicListEvent();
			EventEngine.post(refreshDynamicListEvent);
		}else{
			showToast("签到失败!");
		}
		onHasSend();
	}
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK && requestCode == TO_PIC_IMAGE) {
			new Thread() {
				public void run() {
					setPhotos();
				};
			}.start();
		} else if (requestCode == TO_PHOTO_IMAGE && resultCode == RESULT_OK) {
			if (mAddImageArray.size() + 1 > 9) {
				Tools.showInfo(mContext, "最多添加9张图片");
			} else {
				File f = new File(Environment.getExternalStorageDirectory()
						+ "/" + "CloudCC" + "/photo/" + imagename);
				try {
					Uri u = Uri.parse(android.provider.MediaStore.Images.Media
							.insertImage(getContentResolver(),
									f.getAbsolutePath(), null, null));
					String imageurl = getAbsoluteImagePath(u);
					AddImageInfo imageInfo = new AddImageInfo();
					imageInfo.setImagePath(imageurl);
					mAddImageArray.add(imageInfo);
					imageGridAdapter = new ImageGridAdapter(this, mAddImageArray);
					addpic.setAdapter(imageGridAdapter);
					addpic.setVisibility(View.VISIBLE);
					setAdapterListener();
				} catch (FileNotFoundException e) {
					Tools.handle(e);
				}
			}
		}
	}

	Handler handler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Tools.showInfo(mContext, "最多添加9张图片");
				break;
			case 2:
				imageGridAdapter = new ImageGridAdapter(EditorActivity.this,
						mAddImageArray);
				addpic.setAdapter(imageGridAdapter);
				addpic.setVisibility(View.VISIBLE);
				setAdapterListener();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void setPhotos() {
		ArrayList<String> picPaths = AppContext.selectPhotos;
		if (mAddImageArray.size() + picPaths.size() > 9) {
			handler2.sendEmptyMessage(1);
			picPaths.clear();
			return;
		} else {
			for (int i = 0; i < picPaths.size(); i++) {
				AddImageInfo imageInfo = new AddImageInfo();
				// Bitmap bitmap=ImageUtils.getimage(picPaths.get(i));
				// String
				// path=ImageUtils.SaveImage(System.currentTimeMillis()+".jpg",
				// ImageUtils.Bitmap2Bytes(bitmap));
				// imageInfo.setBitmap(bitmap);
				imageInfo.setImagePath(picPaths.get(i));
				mAddImageArray.add(imageInfo);
			}
			if (mAddImageArray.size() > 9) {
				handler2.sendEmptyMessage(1);
				picPaths.clear();
				return;
			} else {
				handler2.sendEmptyMessage(2);
			}
			picPaths.clear();
		}
	}

	@Override
	protected void onDestroy() {
		unRegister();
		LocationManager.getInstance().unregisterlistener(mListener);
		try {
			AppContext.isSelectedNum = 0;
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onDestroy();
	}

	public String getAbsoluteImagePath(Uri uri) {
		// can post image
		String[] proj = { MediaStore.Images.Media.DATA };
		@SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(uri, proj, // Which columns to return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)

		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private BDLocationListener mListener = new BDLocationListener() {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (null != location
					&& location.getLocType() != BDLocation.TypeServerError) {
				LocationManager.getInstance().stopRequestLocal();
				currentLoc = new MapLocation();
				currentLoc.setAddress(LocationManager.getDetailAddr(location,
						false));
				currentLoc.setLatitude(location.getLatitude());
				currentLoc.setLongitude(location.getLongitude());
				currentLoc.setName(LocationManager.getDetailAddr(location,
						false));
				tvAddress.setText(currentLoc.getAddress());

			} else {
				if (null != location) {
					showToast("定位失败，请重试! 错误码:" + location.getLocType());
				}
			}
		}
	};

	@Override
	public int getLayoutId() {
		return R.layout.map_editor;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}
}
